package com.my.system.dao.order;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.my.system.dao.DataBaseConnection;
import com.my.system.object.order.OrderItem;

public class OrderItemDao {
	private static Connection con = null;
	private static PreparedStatement psta = null;
	private static ResultSet rs = null;
	static {
		con = DataBaseConnection.getConnection();
	}

	public static boolean insertItem(OrderItem order) {
		String sql = "insert into order_item(" + "amount," + "memo,"
				+ "order_id" + ",product_id" + ")values(?,?,?,?)";
		try {
			psta = con.prepareStatement(sql);
			psta.setInt(1, order.getAmount());
			psta.setString(2, order.getMemo());
			psta.setInt(3, order.getOrder_id());
			psta.setInt(4, order.getProduct_id());
			con.setAutoCommit(false);
			int i = psta.executeUpdate();
			con.commit();
			con.setAutoCommit(true);
			if (i > 0) {
				return true;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			try {
				con.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			try {
				if (psta != null) {
					psta.close();
				}
				if (rs != null) {
					psta.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return false;
	}

	public static List<OrderItem> seachAllItem(int order_id) {
		String sql = "select * from order_item where order_id=?";
		List<OrderItem> items = new ArrayList<>();
		OrderItem order = null;
		try {
			psta = con.prepareStatement(sql);
			psta.setInt(1, order_id);
			rs = psta.executeQuery();
			while (rs.next()) {
				int id = rs.getInt(1);
				int amount = rs.getInt(2);
				String memo = rs.getString(3);
				int order_id1 = rs.getInt(4);
				int product_id = rs.getInt(5);
				order = new OrderItem(id, amount, memo, order_id1, product_id);
				items.add(order);
			}
			if (items.size() > 0) {
				return items;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (psta != null) {
					psta.close();
				}
				if (rs != null) {
					psta.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return null;
	}

}
